package hoyo.zqy.pet.service.impl;

import hoyo.zqy.basic.exception.BusinessException;
import hoyo.zqy.basic.service.IBaiduAiAuditService;
import hoyo.zqy.basic.util.*;
import hoyo.zqy.order.domain.OrderPetAcquisition;
import hoyo.zqy.order.mapper.OrderPetAcquisitionMapper;
import hoyo.zqy.org.domain.Employee;
import hoyo.zqy.org.domain.Shop;
import hoyo.zqy.org.mapper.EmployeeMapper;
import hoyo.zqy.org.mapper.ShopMapper;
import hoyo.zqy.pet.domain.SearchMasterMsg;
import hoyo.zqy.pet.domain.SearchMasterMsgAuditLog;
import hoyo.zqy.pet.dto.OrderDto;
import hoyo.zqy.pet.mapper.SearchMasterMsgAuditLogMapper;
import hoyo.zqy.pet.mapper.SearchMasterMsgMapper;
import hoyo.zqy.pet.query.SearchMasterMsgQuery;
import hoyo.zqy.pet.service.ISearchMasterMsgService;
import hoyo.zqy.basic.service.impl.BaseServiceImpl;
import hoyo.zqy.user.domain.Logininfo;
import hoyo.zqy.user.domain.User;
import hoyo.zqy.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     * 发布寻主消息
     * @param searchMasterMsg
     * @return
     */
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg,HttpServletRequest request) {
        //获取登录信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //获取登录人信息
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //保存发布人id
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);//获得自增长id

        //百度AI智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getTitle()
                + searchMasterMsg.getName() + searchMasterMsg.getCoatColor());
        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        if (boo1 && boo2){
            //审核通过： 3.保存到数据库 4.记录审核日志 5.发短信或邮箱告诉店铺管理员去接回宠物
            //1.改state=1
            searchMasterMsg.setState(1);
            //2.分配最近50公里以内的店铺
            List<Shop> shops = shopMapper.loadAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            //判断是否找到店铺
            if (nearestShop==null){
                //没有就放入寻主池
                searchMasterMsg.setState(3);
            }  else {
                //找到店铺
                searchMasterMsg.setShopId(nearestShop.getId());
                //发送短信或者邮箱通知
                Employee employee = employeeMapper.loadById(nearestShop.getAdminId());
                //SmsUtils.sendSms(employee.getPhone(),"有宠物来了，请在1s内处理地址在【"+searchMasterMsg.getAddress()+"】,联系人【"+user.getPhone()+"】");
                System.out.println("有宠物来了，请在1s内处理地址在【"+searchMasterMsg.getAddress()+"】,联系人【"+user.getPhone()+"】");
            }
            searchMasterMsgMapper.update(searchMasterMsg);
            //记录日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);
            //智能审核
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);

        }else {
            //审核失败: 1.改状态state=-1 2.记录审核日志 3.发短信或邮箱告诉用户重新修改资料再分布
            searchMasterMsg.setState(-1);
            searchMasterMsgMapper.update(searchMasterMsg);
            //记录日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);
            //智能审核
            log.setNote("审核失败");
            //发送短信或者邮箱通知
            //SmsUtils.sendSms(employee.getPhone(),"有宠物来了，请在1s内处理地址在【"+searchMasterMsg.getAddress()+"】,联系人【"+user.getPhone()+"】");
            searchMasterMsgAuditLogMapper.save(log);
            System.out.println("抱歉审核失败，有敏感信息");
            return AjaxResult.me().setSuccess(false).setMsg("抱歉审核失败，有敏感信息");
        }
        return AjaxResult.me();
    }

    /**
     * 用户查询
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //获取数据
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //根据id查询用户
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //存入userid
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    /**
     * 管理员查询待处理寻主消息
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //待处理
        query.setState(1);
        //获取数据
        Logininfo logininfo = LoginContext.getLogininfo(request);
        // //区分平台管理员或店铺管理员
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null){
            //店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    /**
     * 店铺管理员不能查询以完成的寻主消息
     * @param query
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query) {
        query.setState(2);
        return super.queryPage(query);
    }

    /**
     * 管理员查询寻主池寻主消息
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query) {
        query.setState(3);
        return super.queryPage(query);
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     * @param order
     */
    @Override
    public void accept(OrderDto orderDto) {
        //判断该订单是否在处理
        OrderPetAcquisition dbOrder = orderPetAcquisitionMapper.loadByMsgId(orderDto.getMsgId());
        //有值代表正在处理
        if (dbOrder!=null && dbOrder.getState()==0){
            throw new BusinessException("已经有人抢先一步");
        }
        //生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(orderDto.getMsgId());
        OrderPetAcquisition order = orderDto2Order(orderDto,msg);
        orderPetAcquisitionMapper.save(order);

        //通知接单人
        System.out.println("有宠物来了，请在1s内处理地址在【"+order.getAddress()+"】");
    }

    private OrderPetAcquisition orderDto2Order(OrderDto orderDto, SearchMasterMsg msg) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(orderDto.getNote());
        //三天后未接单后取消
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+3*24*60*60*1000));
        //修改状态
        order.setState(0);
        //价格
        order.setPrice(msg.getPrice());
        //用户id
        order.setUserId(msg.getUserId());
        //店铺id
        order.setShopId(msg.getShopId());
        //地址
        order.setAddress(msg.getAddress());
        order.setEmpId(orderDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }


}
